/*------生成随机数------*/
const config = require("./config.js");
const sha1 = require("./sha1.js");
const appkey = config.APPKEY;
const appsecret = config.APPSECRET;

/*-------生成随机数--------*/
exports.generate_random = (number = 6) => {
  const source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < number; i++) {
    let index = Math.round(Math.random() * 62);
    result += source[index];
  };
  return result;
};
/*-------生成签名--------*/
exports.generate_sign = (nonceStr, data) => {
  let sign_arr = [`appkey=${appkey}`, `appsecret=${appsecret}`, `nonceStr=${nonceStr}`];
  for (let item in data) {
    sign_arr.push(`${item}=${data[item]}`);
  };
  let sign_str = sign_arr.sort().join("&");
  // console.log(sign_str);
  let sign = sha1(sign_str);
  return sign;
};

function sortfun(a,b) {
  return a-b;
}

/*--------验证手机号是否正确------*/
exports.phone_validate = (phone) => {
  if (/^[1][3,4,5,7,8][0-9]{9}$/.test(phone)) {
    return true;
  } else {
    return false;
  }
};

exports.email_validate = (phone) => {
  if (/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(phone)) {
    return true;
  } else {
    return false;
  }
};

exports.validate = function(str, reg) {
  if (!str || !reg) {
    return false;
  }

  return reg.test(str);
}

exports.isMoney = function(str) {
  if(str == 0 || str == '0') {
    return true;
  }
  var myreg = /^[0-9]+(.[0-9]{1,2})?$/;
  return this.validate(str, myreg);
}

exports.isNumber = function (str) {
  var myreg = /^[1-9]+[0-9]*]*$/;
  return this.validate(str, myreg);
}

exports.moneyStyle = function(amount) {
  if (amount == null) {
    return amount;
  }
  return amount.toFixed(2);
}

exports.moneyStyle1 = function(amount) {
  if (amount == null) {
    return amount;
  }
  return amount.toFixed(1);
}

exports.shortTime = function(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;

  var result = this.timestampFormate('yyyy-MM-dd', dateTimeStamp);

  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else if (minC < 1) {
    result = "刚刚";
  }
  return result;
};

exports.shortTime2 = function(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;

  var result = this.timestampFormate('yyyy年M月d日 hh:mm', dateTimeStamp);

  if (monthC >= 1) {

  } else if (weekC >= 1) {

  } else if (dayC >= 3) {

  } else if (dayC >= 2) {
    // result = this.timestampFormate('前天 hh:mm', dateTimeStamp);
  } else if (isYestday(new Date(dateTimeStamp))) {
    result = this.timestampFormate('昨天 hh:mm', dateTimeStamp);
  } else if (hourC >= 1) {
    result = this.timestampFormate('今天 hh:mm', dateTimeStamp);
  } else if (minC >= 10) {
    result = this.timestampFormate('今天 hh:mm', dateTimeStamp);
  } else if (minC < 10) {
    result = "刚刚";
  }
  return result;
};

exports.calAge = function (dateTimeStamp) {
  if(!dateTimeStamp) {
    return 0;
  }
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return 0;
  }
  
  return parseInt(diffValue/day/365);
};

function isYestday(theDate) {
  var date = (new Date());    //当前时间
  var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); //今天凌晨
  var yestday = new Date(today - 24 * 3600 * 1000).getTime();
  return theDate.getTime() < today && yestday <= theDate.getTime();
}

exports.timestampFormate = function(fmt, date) {
  if (!date) {
    return;
  }
  return this.dateFormate(fmt, new Date(date));
}

exports.tf = function(fmt, date) {
  return this.timestampFormate(fmt, date);
}

exports.dateFormate = function(fmt, date) { //author: meizz   
  var o = {
    "M+": date.getMonth() + 1, //月份   
    "d+": date.getDate(), //日   
    "h+": date.getHours(), //小时   
    "m+": date.getMinutes(), //分   
    "s+": date.getSeconds(), //秒   
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
    "S": date.getMilliseconds() //毫秒   
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

exports.isEmpty = function(text) {
  return text == null || text == '';
}

exports.stringToDate = function(dateStr, separator) {
  if (!separator) {
    separator = "-";
  }
  var dateArr = dateStr.split(separator);
  var year = parseInt(dateArr[0]);
  var month;
  //处理月份为04这样的情况                         
  if (dateArr[1].indexOf("0") == 0) {
    month = parseInt(dateArr[1].substring(1));
  } else {
    month = parseInt(dateArr[1]);
  }
  var day = parseInt(dateArr[2]);
  var date = new Date(year, month - 1, day);
  return date;
}

exports.shortTime3 = function(ts) {
  if (ts == null) {
    return null;
  }

  var date = new Date(ts)
  var mon = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var min = date.getMinutes();
  var weekday = date.getDay();

  var wt = '';
  switch (weekday) {
    case 0:
      wt = '周日';
      break;
    case 1:
      wt = '周一';
      break;
    case 2:
      wt = '周二';
      break;
    case 3:
      wt = '周三';
      break;
    case 4:
      wt = '周四';
      break;
    case 5:
      wt = '周五';
      break;
    case 6:
      wt = '周六';
      break;
  }

  return mon + '月' + day + '日' + '（' + wt + '）' + this.dateFormate('hh:mm', date);
};

exports.downTime = function(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = dateTimeStamp - now;
  if (diffValue < 0) {
    return null;
  }
  var dayC = parseInt(diffValue / day);
  var hourC = parseInt((diffValue - dayC * day) / hour);
  var minC = parseInt((diffValue - dayC * day - hourC * hour) / minute);

  if (dayC > 0 || hourC > 0 || minC > 0) {
    if (dayC > 0) {
      return dayC + '天' + (hourC > 0 ? hourC + '小时' : '');
    } else if (hourC > 0) {
      return hourC + '小时' + (minC > 0 ? minC + '分钟' : '');
    } else {
      return minC + '分钟';
    }
  }
  return null;
};

exports.downTime1 = function (dateTimeStamp) {
  var sec = 1000;
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = dateTimeStamp - now;
  if (diffValue < 0) {
    return null;
  }
  var dayC = parseInt(diffValue / day);
  var hourC = parseInt((diffValue - dayC * day) / hour);
  var minC = parseInt((diffValue - dayC * day - hourC * hour) / minute);

  var secC = parseInt((diffValue - dayC * day - hourC * hour - minC * minute) / sec);

  var hours = (hourC<10?('0'+hourC):hourC);
  var mins = (minC < 10 ? ('0' + minC) : minC);
  var secs = (secC < 10 ? ('0' + secC) : secC);

  return hours + '时 ' + mins+'分 '+secs+'秒';
};

exports.putCache = function(key, value) {
  if (key) {
    wx.setStorageSync(key, value);
  }
}

exports.getFromCache = function(key) {
  if (key) {
    return wx.getStorageSync(key);
  }
  return;
}

exports.changeTab = function(e, that) {
  var index = e.currentTarget.dataset.index;
  if (index == that.data.index) {
    return;
  }
  that.setData({
    index: index
  });
  that.refresh();
}

exports.showModal = function () {
  // wx.setNavigationBarColor({
  //   frontColor: '#ffffff',
  //   backgroundColor: '#2f3d74',
  //   animation:{
  //     duration:0
  //   }
  // });
}

exports.hideModal = function () {
  // wx.setNavigationBarColor({
  //   frontColor: '#ffffff',
  //   backgroundColor: '#577BEF',
  // });
}

exports.shortNumber = function (num) {
  if (num == null) {
    return 0;
  }

  if (num >= 100000000) {
    num = num / 100000000;
    num = num.toFixed(2) + "亿";
  } else if (num >= 100000) {
    num = num / 10000;
    num = parseInt(num) + "万";
  } else if (num >= 10000) {
    num = num / 10000;
    num = num.toFixed(2) + "万";
  }

  return num;
}

exports.formatMoney = function (num) {
  if (num == null) {
    return 0;
  }

  return num.toFixed(2);
}

exports.shortDiscount = function (num) {
  if (num == null) {
    return 10;
  }

  return (num*10).toFixed(1);
}